package com.scholarship.common.config;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * 重写Shiro自带角色权限管理器
 * roles[admin]->roles[admin,student]
 * @Author Z.J.H
 * @create 2021/9/10 11:04
 */
public class ShiroRoleFilter extends RolesAuthorizationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {

        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }

        for(String roleName : rolesArray) {
            if(subject.hasRole(roleName)) {
                return true;
            }
        }
        return false;
    }
}
